package com.xju.servlet;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;

import com.xju.dao.CollegeDao;
import com.xju.dao.CollegeDaoImpl;
import com.xju.entity.College;

@WebServlet("/api/colleges")
public class CollegeServlet extends HttpServlet {
    private final CollegeDao collegeDao = new CollegeDaoImpl(); // 使用正确的DAO
    private final Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        try {
            List<College> colleges = collegeDao.findAllColleges();
            response.getWriter().write(gson.toJson(colleges));
        } catch (Exception e) {
            sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }

    private void sendErrorResponse(HttpServletResponse response, int statusCode, String message)
            throws IOException {
        response.setStatus(statusCode);
        response.getWriter().write(gson.toJson(Collections.singletonMap("error", message)));
    }
}